package com.dragon.user_service.api.RPC;

import com.dragon.user_service.annotation.AuthCheck;
import com.dragon.user_service.constant.UserConstant;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Component
public class permissionTemp implements permissionService {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Transactional
    @Override
    public void bindDefaultRole(Long userId) {
        jdbcTemplate.update(
                "INSERT INTO user_roles (user_id, role_id) VALUES (?, 3)",
                userId
        );
        System.out.println("权限服务:bindDefaultRole接口已调用 " + 200 + "ok");
    }

    @Override
    public String getUserRoleCode(Long userId) {

        String sql = "SELECT r.role_code " +
                "FROM roles r " +
                "INNER JOIN user_roles ur ON r.role_id = ur.role_id " +
                "WHERE ur.user_id = ?";
        try {
            System.out.println("权限服务:getUserRoleCode " + 200 + "ok");
            return jdbcTemplate.queryForObject(sql, String.class, userId);
        } catch (EmptyResultDataAccessException e) {
            return null; // 无结果时返回 null
        }
    }

    @Override
    @Transactional
    @AuthCheck(mustRole = UserConstant.SUPER_ADMIN_ROLE)
    public void upgradeToAdmin(Long userId) {
        jdbcTemplate.update(
                "UPDATE user_roles SET role_id = 2 WHERE user_id = ?",
                userId
        );
        System.out.println("权限服务:upgradeToAdmin " + 200 + "ok");
    }

    @Override
    @Transactional
    @AuthCheck(mustRole = UserConstant.SUPER_ADMIN_ROLE)
    public void downgradeToUser(Long userId) {
        jdbcTemplate.update(
                "UPDATE user_roles SET role_id = 1 WHERE user_id = ?",
                userId
        );
        System.out.println("权限服务:downgradeToUser " + 200 + "ok");
    }
}
